import { ref, computed } from 'vue';

export enum LoginStateEnum {
  LOGIN,
  REGISTER,
  RESET_PASSWORD,
  MOBILE,
  QR_CODE,
}

const currentState = ref(LoginStateEnum.LOGIN);

export function useLoginState() {
  function setLoginState(state: LoginStateEnum) {
    currentState.value = state;
  }

  const getLoginState = computed(() => currentState.value);

  function handleBackLogin() {
    setLoginState(LoginStateEnum.LOGIN);
  }

  return { setLoginState, getLoginState, handleBackLogin };
}

export function useFormValid(formRef: any) {
  const validate = computed(() => {
    const form = formRef.value;
    return form?.validate ?? ((_nameList?: any) => Promise.resolve());
  });

  async function validForm() {
    const form = formRef.value;
    if (!form) return;
    const data = await form.validate();
    return data;
  }

  return { validate, validForm };
}

export function useFormRules() {
  // 用户名验证
  const validateUsername = (_rule: any, value: string) => {
    if (!value) {
      return Promise.reject('请输入用户名');
    }
    return Promise.resolve();
  };

  // 密码验证
  const validatePassword = (_rule: any, value: string) => {
    if (!value) {
      return Promise.reject('请输入密码');
    }
    return Promise.resolve();
  };

  // 手机号验证
  const validateMobile = (_rule: any, value: string) => {
    if (!value) {
      return Promise.reject('请输入手机号');
    }
    if (!/^1[3-9]\d{9}$/.test(value)) {
      return Promise.reject('手机号格式不正确');
    }
    return Promise.resolve();
  };

  // 验证码验证
  const validateSmsCode = (_rule: any, value: string) => {
    if (!value) {
      return Promise.reject('请输入验证码');
    }
    if (!/^\d{6}$/.test(value)) {
      return Promise.reject('验证码必须是6位数字');
    }
    return Promise.resolve();
  };

  // 租户名验证
  const validateTenantName = (_rule: any, value: string) => {
    if (!value && window.__VITE_TENANT_ENABLE__ === 'true') {
      return Promise.reject('请输入租户名');
    }
    return Promise.resolve();
  };

  return {
    usernameRule: [{ validator: validateUsername, trigger: 'blur' }],
    passwordRule: [{ validator: validatePassword, trigger: 'blur' }],
    phoneRule: [{ validator: validateMobile, trigger: 'blur' }],
    smsCodeRule: [{ validator: validateSmsCode, trigger: 'blur' }],
    tenantNameRule: [{ validator: validateTenantName, trigger: 'blur' }],
  };
}
